<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use Dotenv\Validator;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Exception\XZXValidationException;
use App\Service\SysRoleService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Psr\Container\ContainerInterface;
use Hyperf\Logger\LoggerFactory;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;

/**
 * Class SysRoleController
 * @package App\Controller
 *
 * @Controller(prefix="/admin/api/sysRole")
 */
class SysRoleController extends AdminBaseController
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var SysRoleService
     */
    protected $SysRoleService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->SysRoleService->get($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'        => 'required|uuid',
                'name'      => 'required|between:2,8|alpha_num',
                'remark'    => 'between:2,20|alpha_num',
                'extraType' => 'required|integer',
                'status'    => 'required|integer|max:1|min:0',                
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid'];         
        $param['createBy']      =  $ext['createBy']; 
        return $this->SysRoleService->edit($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function add(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'name'      => 'required|between:4,8|alpha_num',
                'remark'    => 'between:4,20|alpha_num',
                // 'type'      => 'required|integer',
                'extraType' => 'required|integer',                
                // 'nodeId'    => 'required|uuid',
                'status'    => 'required|integer|max:1|min:0',

            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid'];         
        $param['createBy']      =  $ext['createBy']; 
        return $this->SysRoleService->add($param);
    }

    /**
     * 删除
     * @PostMapping(path = "del")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function del(RequestInterface $request)
    {

        // $validator = $this->validationFactory->make(
        //     $request->all(),
        //     [
        //         'id' => 'required|uuid',
        //     ],
        // );

        // if ($validator->fails()){
        //     // Handle exception
        //     $errorMessage = $validator->errors()->first();  
        //     throw new XZXValidationException($errorMessage);
        // }

        // $param = $request->all();
        // return $this->SysRoleService->del($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page'          => 'required|integer|min:1',
                'limit'         => 'required|integer|min:1',
                'search.type'   => 'sometimes|required|integer|max:1|min:0',
                'search.status' => 'sometimes|required|integer|max:1|min:0',                
                'search.name'   => 'sometimes|required|between:4,8|alpha_num',                
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        
        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid'];

        if(isset($param['search'])){
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'name');
            CustomUtils::xzxAddSearch($param, $search, 'type');
            CustomUtils::xzxAddSearch($param, $search, 'status');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }
        
        
        return $this->SysRoleService->list($param);
    }

    /**
     * 查询 Options
     * @PostMapping(path = "getOptions")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */    
    public function getOptions (RequestInterface $request) {
        $param = $request->all();
        return $this->SysRoleService->getOptions($param);
    }
   
    /**
     * 设置权限
     * @PostMapping(path = "setaccess")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */  
    public function setAccess (RequestInterface $request) {

        $param = $request->all();
        return $this->SysRoleService->setAccess($param);        
    }

    /**
     * 查询权限
     * @PostMapping(path = "getaccess")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */  
    public function getAccess (RequestInterface $request) {

        $param = $request->all();
        return $this->SysRoleService->getAccess($param);        
    }
}